package finance

import (
	"encoding/csv"
	"fmt"
	"os"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
	"go-papers/models"
	"go-papers/pkg/lognew"
	"go-papers/tools"
	"go-papers/tools/app"
)

func GetShareList(c *gin.Context) {
	var data models.Order
	var err error
	var pageSize = 10
	var pageIndex = 1

	if size := c.Request.FormValue("pageSize"); size != "" {
		pageSize = tools.StrToInt(err, size)
	}
	if index := c.Request.FormValue("pageIndex"); index != "" {
		pageIndex = tools.StrToInt(err, index)
	}

	data.OrderNo = c.Request.FormValue("orderNo")
	data.OrderName = c.Request.FormValue("orderName")
	data.BrandName = c.Request.FormValue("brandName")
	data.OrganName = c.Request.FormValue("organName")
	data.CourseName = c.Request.FormValue("courseName")
	data.OrderStatus = c.Request.FormValue("orderStatus")

	if index := c.Request.FormValue("memberId"); index != "" {
		data.MemberId = tools.StrToInt(err, index)
	}
	if index := c.Request.FormValue("memberMomId"); index != "" {
		data.MemberMomId = tools.StrToInt(err, index)
	}
	if index := c.Request.FormValue("courseId"); index != "" {
		data.CourseId = tools.StrToInt(err, index)
	}
	data.MemberPhone = c.Request.FormValue("memberPhone")
	data.MemberName = c.Request.FormValue("memberName")
	data.MemberMomName = c.Request.FormValue("memberMomName")

	data.PayType = c.Request.FormValue("payType")
	data.PayNo = c.Request.FormValue("payNo")
	data.PayTime = c.Request.FormValue("payTime")
	data.ShareType = c.Request.FormValue("shareType")
	if data.ShareType == "" {
		data.ShareType, _ = c.Params.Get("shareType")
	}

	data.ShareStatus = c.Request.FormValue("shareStatus")

	data.AddressSearch = c.Request.FormValue("addressSearch") //所在地区
	data.Address = c.Request.FormValue("address")             //小区名称
	data.OrganName = c.Request.FormValue("organName")         //机构名称
	data.BrandName = c.Request.FormValue("brandName")         //品牌名称

	data.PayTimeStart = c.Request.FormValue("payTimeStart")
	data.PayTimeEnd = c.Request.FormValue("payTimeEnd")

	data.ShareTimeStart = c.Request.FormValue("shareTimeStart") // 分佣金 起始时间
	data.ShareTimeEnd = c.Request.FormValue("shareTimeEnd")     // 分佣金  结束时间

	data.DataScope = tools.GetUserIdStr(c)
	result, count, err := data.GetSharePageFiance(pageSize, pageIndex) // 佣金明细
	if err != nil {
		app.ApiResp(c, -1, "数据查询失败："+err.Error(), nil)
		return
	}
	app.PageOK(c, result, count, pageIndex, pageSize, "")
}

func DownMoneyList(c *gin.Context) {
	var data models.Order
	var err error
	var pageSize = 10
	var pageIndex = 1

	if size := c.Request.FormValue("pageSize"); size != "" {
		pageSize = tools.StrToInt(err, size)
	}
	if index := c.Request.FormValue("pageIndex"); index != "" {
		pageIndex = tools.StrToInt(err, index)
	}

	data.OrderNo = c.Request.FormValue("orderNo")
	data.OrderName = c.Request.FormValue("orderName")
	data.BrandName = c.Request.FormValue("brandName")
	data.OrganName = c.Request.FormValue("organName")
	data.CourseName = c.Request.FormValue("courseName")
	data.OrderStatus = c.Request.FormValue("orderStatus")

	if index := c.Request.FormValue("memberId"); index != "" {
		data.MemberId = tools.StrToInt(err, index)
	}
	if index := c.Request.FormValue("memberMomId"); index != "" {
		data.MemberMomId = tools.StrToInt(err, index)
	}
	if index := c.Request.FormValue("courseId"); index != "" {
		data.CourseId = tools.StrToInt(err, index)
	}
	data.MemberPhone = c.Request.FormValue("memberPhone")
	data.MemberName = c.Request.FormValue("memberName")
	data.MemberMomName = c.Request.FormValue("memberMomName")

	data.PayType = c.Request.FormValue("payType")
	data.PayNo = c.Request.FormValue("payNo")
	data.PayTime = c.Request.FormValue("payTime")
	data.ShareType = c.Request.FormValue("shareType")
	data.ShareStatus = c.Request.FormValue("shareStatus")

	data.AddressSearch = c.Request.FormValue("addressSearch") //所在地区
	data.Address = c.Request.FormValue("address")             //小区名称
	data.OrganName = c.Request.FormValue("organName")         //机构名称
	data.BrandName = c.Request.FormValue("brandName")         //品牌名称

	data.PayTimeStart = c.Request.FormValue("payTimeStart")
	data.PayTimeEnd = c.Request.FormValue("payTimeEnd")

	data.ShareTimeStart = c.Request.FormValue("shareTimeStart") // 分佣金 起始时间
	data.ShareTimeEnd = c.Request.FormValue("shareTimeEnd")     // 分佣金  结束时间

	data.DataScope = tools.GetUserIdStr(c)
	result, count, err := data.GetSharePage(pageSize, pageIndex)
	if err != nil {
		app.ApiResp(c, -1, "数据查询失败："+err.Error(), nil)
		return
	}
	//订单编号	会员姓名	会员ID	品牌名称	机构名称	课程名称	提交时间	支付时间	社区达人姓名	社区达人ID
	// 订单金额	交易佣金比例	机构佣金金额	佣金状态	结算时间 结算明细 备注
	header := []string{"订单ID", "订单编号", "会员姓名", "会员ID", "品牌名称", "机构名称", "课程名称", "提交时间", "支付时间",
		"社区达人姓名", "社区达人ID", "订单金额", "交易佣金比例", "机构佣金金额", "佣金状态", "结算时间", "结算明细", "备注"} //标题
	cellist := [][]string{
		header,
	}
	cellist = DataToStringV4(result, cellist)

	page := count/pageSize + 1

	for i := 2; i <= page; i++ {
		pageIndex = i
		result, _, _ = data.GetSharePage(pageSize, pageIndex)
		if len(result) <= 0 {
			break
		}
		cellist = DataToStringV4(result, cellist)
	}

	// 创建文件
	filepath := "static/"
	filename := "OrderShare_" + time.Now().Format("20060102150405") + ".csv"
	newFile, err := os.Create(filepath + filename)
	if err != nil {
		app.OK(c, nil, err.Error())
		return
	}
	defer func() {
		newFile.Close()

		err := os.Remove(filepath + filename)
		if err != nil {
			// 删除失败
			lognew.Info(c, "导出文件-清理失败", lognew.Fields{"file": filepath + filename, "err": err.Error()})
		}

	}()

	// 写入UTF-8
	newFile.WriteString("\xEF\xBB\xBF") // 写入UTF-8 BOM，防止中文乱码
	// 写数据到csv文件
	w := csv.NewWriter(newFile)
	// WriteAll方法使用Write方法向w写入多条记录，并在最后调用Flush方法清空缓存。
	w.WriteAll(cellist)
	w.Flush()

	c.File(filepath + filename)

}

// OrganTeacher
//订单编号	会员姓名	会员ID	品牌名称	机构名称	课程名称	提交时间	支付时间	社区达人姓名	社区达人ID
// 订单金额	交易佣金比例	佣金状态	结算时间 结算明细 备注
func DataToStringV4(list []models.OrderShareList, data [][]string) [][]string {
	for i := 0; i < len(list); i++ {
		op := fmt.Sprintf("%.2f", list[i].OrderPrice)
		op2 := fmt.Sprintf("%.2f", list[i].SharePrice)
		op3 := fmt.Sprintf("%.2f", list[i].ShareRate)
		context := []string{
			strconv.Itoa(list[i].OrderId),
			list[i].OrderNo,
			list[i].MemberName,
			strconv.Itoa(list[i].MemberId),
			list[i].BrandName,
			list[i].OrganName,
			list[i].CourseName,
			list[i].CreatedAt.Format("2006-01-02 15:04:05"),
			list[i].PayTime,
			list[i].MemberMomName,
			strconv.Itoa(list[i].MemberMomId),
			op,
			op2,
			op3,
			list[i].ShareStatus,
			list[i].ShareTime,
			list[i].ShareDesc,
			list[i].ShareInfo,
		}
		data = append(data, context)
	}
	return data
}
